package com.ask.service.Impl;

import com.ask.dto.GoodsSalesDTO;
import com.ask.entity.Orders;
import com.ask.mapper.OrderMapper;
import com.ask.mapper.UserMapper;
import com.ask.service.ReportService;
import com.ask.service.WorkSpaceService;
import com.ask.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkSpaceService workSpaceService;


    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);

        // 获取每日的营业额列表
        List<Double> turnOverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 获取每日的开始与结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 构造条件查询
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            // 查询order表
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnOverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnOverList, ",")).
                build();
    }

    private static List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 用户数量统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        // 统计每日的用户数量
        List<Integer> totalUserNumList = new ArrayList<>();
        List<Integer> dayUserNumList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 获取每日的开始与结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 构造查询条件
            // 先查询截止当天的用户数量
            Map map = new HashMap<>();
            map.put("endTime", endTime);
            Integer totalNum = userMapper.countByMap(map);
            totalUserNumList.add(totalNum);
            // 再查询当天新增的用户数量
            map.put("beginTime", beginTime);
            Integer dayNum = userMapper.countByMap(map);
            dayUserNumList.add(dayNum);
        }

        return UserReportVO.builder().
                dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(dayUserNumList, ","))
                .totalUserList(StringUtils.join(totalUserNumList, ','))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // 获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>(); // 订单数列表
        List<Integer> validOrderCountList = new ArrayList<>(); // 有效订单数列表
        Integer totalOrderCount = 0;
        Integer totalValidOrderCount = 0;
        for (LocalDate date : dateList) {
            // 获取每日的开始与结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 获取当日的总订单数
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer dayOrderNum = orderMapper.countByMap(map);
            totalOrderCount += dayOrderNum;
            orderCountList.add(dayOrderNum);
            // 获取当日的有效订单数
            map.put("status", Orders.COMPLETED);
            Integer dayValidOrderNum = orderMapper.countByMap(map);
            totalValidOrderCount += dayValidOrderNum;
            validOrderCountList.add(dayValidOrderNum);
        }

        // 计算订单完成率
        Double orderCompletedRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletedRate = totalValidOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletedRate)
                .build();
    }


    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        // 从对象列表中提取属性列表
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<String> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ','))
                .numberList(StringUtils.join(numbers, ','))
                .build();
    }


    /**
     * 导出Excel报表接口
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 获取时间区间
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        // 获取总览数据
        BusinessDataVO businessData = workSpaceService.getDayBusinessData(beginTime, endTime);

        // 加载模板文件到excel中
        InputStream in = this.getClass().getClassLoader().
                getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 填充数据--时间
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间" + dateBegin + "至" + dateEnd);

            // 获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            // 获取第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO dayBusinessData = workSpaceService.getDayBusinessData
                        (LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(dayBusinessData.getTurnover());
                row.getCell(3).setCellValue(dayBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(dayBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(dayBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(dayBusinessData.getNewUsers());
            }
            // 3. 通过输出流将excel下载到浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
